<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <el-select
          clearable
          v-model="dataForm.projectId"
          placeholder="所属项目"
        >
          <el-option
            v-for="item in projectList"
            :key="item.id"
            :label="item.projectName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          clearable
          v-model="dataForm.company"
          placeholder="车辆所属公司"
        >
          <el-option
            v-for="item in companyList"
            :key="item.id"
            :label="item.companyName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="dataForm.carCode"
          placeholder="车牌号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select clearable v-model="dataForm.status" placeholder="台账状态">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 添加筛选条件：审核状态，只有管理员才能看到 -->
      <el-form-item>
        <el-select
          clearable
          v-model="dataForm.auditstatus"
          placeholder="审核状态"
          v-if="isAuth('generator:bcarledger:audit')"
        >
          <el-option
            v-for="item in auditList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="出除渣场时间">
        <el-date-picker
          v-model="dateRange1"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          @change="timeChange($event, 1)"
          clearable
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="进消纳场时间">
        <el-date-picker
          v-model="dateRange2"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          @change="timeChange($event, 2)"
          clearable
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList('query')">查询</el-button>
        <el-button
          type="danger"
          v-if="isAuth('generator:bcarledger:delete')"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
          >批量删除</el-button
        >
        <el-button
          v-if="isAuth('generator:bcarledger:audit')"
          type="success"
          @click="auditHandle(null, 'batch')"
          :disabled="dataListSelections.length <= 0"
          >批量审核</el-button
        >
        <el-button
          v-if="isAuth('generator:bcarledger:handleExport')"
          @click="handleExport()"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        prop="projectName"
        header-align="center"
        align="center"
        label="所属项目"
      >
      </el-table-column>
      <el-table-column
        prop="company"
        header-align="center"
        align="center"
        label="车辆所属公司"
      >
      </el-table-column>
      <el-table-column
        prop="carCode"
        header-align="center"
        align="center"
        label="车牌号"
      >
      </el-table-column>
      <el-table-column
        prop="carCodeUrl"
        header-align="center"
        align="center"
        label="出除渣场车牌照片"
      >
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.carCodeUrl"
            :src="getArr(scope.row.carCodeUrl)[0]"
            :preview-src-list="getArr(scope.row.carCodeUrl)"
            style="width: 64px; height: 36px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="coachUrl"
        header-align="center"
        align="center"
        label="出除渣场车斗照片"
      >
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.coachUrl"
            :src="getArr(scope.row.coachUrl)[0]"
            :preview-src-list="getArr(scope.row.coachUrl)"
            style="width: 64px; height: 36px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="snapTime"
        header-align="center"
        align="center"
        label="出除渣场时间"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.snapTime"> {{ scope.row.snapTime }}</span>
          <span v-else> --</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="numberplateUrl"
        header-align="center"
        align="center"
        label="进消纳场车牌照片"
      >
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.numberplateUrl"
            :src="getArr(scope.row.numberplateUrl)[0]"
            :preview-src-list="getArr(scope.row.numberplateUrl)"
            style="width: 64px; height: 36px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="railwayCarriagehUrl"
        header-align="center"
        align="center"
        label="进消纳场车斗照片"
      >
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.railwayCarriagehUrl"
            :src="getArr(scope.row.railwayCarriagehUrl)[0]"
            :preview-src-list="getArr(scope.row.railwayCarriagehUrl)"
            style="width: 64px; height: 36px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="photographTime"
        header-align="center"
        align="center"
        label="进消纳场时间"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.photographTime">
            {{ scope.row.photographTime }}</span
          >
          <span v-else> --</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        label="台账状态"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.status === 0">异常</div>
          <div v-if="scope.row.status === 1">合格</div>
          <div v-if="scope.row.status === 2">待核算</div>
        </template>
      </el-table-column>

      <el-table-column
        v-if="isAuth('generator:bcarledger:audit')"
        prop="auditstatus"
        header-align="center"
        align="center"
        label="审核状态"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.audit === 0">未审核</div>
          <div v-if="scope.row.audit === 1">通过</div>
          <div v-if="scope.row.audit === 2">不通过</div>
        </template>
      </el-table-column>

      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            v-if="isAuth('generator:bcarledger:delete')"
            type="text"
            size="small"
            @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
          <el-button type="text" size="small" @click="checkHandle(scope.row.id)"
            >轨迹地图</el-button
          >
          <el-button type="text" size="small" @click="infoHandle(scope.row.id)"
            >异常信息</el-button
          >
          <el-button
            v-if="isAuth('generator:bcarledger:audit')"
            type="text"
            size="small"
            @click="auditHandle(scope.row.id, 'single', scope.row)"
            >审核</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageParams.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageParams.limit"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <!-- 弹窗, 新增 / 修改 / 审核-->
    <leader-track v-if="trackVisible" ref="leaderTrack"></leader-track>
    <leader-info
      v-if="infoVisible"
      ref="leaderInfo"
      :ledgerId="tempid"
    ></leader-info>
    <ledger-audit v-if="auditVisible" ref="ledgerAudit"></ledger-audit>
  </div>
</template>

<script>
import leaderTrack from "./leaderTrack.vue";
import leaderInfo from "./leaderInfo.vue";
import ledgerAudit from "./ledgerAudit.vue";
export default {
  data() {
    return {
      tempid: "",
      projectList: [],
      dataForm: {
        reportId: null,
        projectId: "",
        company: "",
        carCode: "",
        auditstatus: "",
        startSnapTime: null,
        endSnapTime: null,
        startDate: null,
        endDate: null,
        status: null,
        selectAll: 0,
      },
      dataList: [],
      pageParams: {
        page: 1,
        limit: 10,
      },
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      trackVisible: false,
      infoVisible: false,
      auditVisible: false,
      dateRange1: [],
      dateRange2: [],
      companyList: [],
      statusList: [
        {
          label: "异常",
          value: 0,
        },
        {
          label: "合格",
          value: 1,
        },
        {
          label: "待核算",
          value: 2,
        },
      ],
      auditList: [
        {
          label: "未审核",
          value: 0,
        },
        {
          label: "通过",
          value: 1,
        },
        {
          label: "不通过",
          value: 2,
        },
      ],
    };
  },
  components: { leaderTrack, leaderInfo, ledgerAudit },
  activated() {
    this.dataForm.reportId = this.$route.query.reportId;
    this.dataForm.carCode = this.$route.query.carCode;

    console.log(Object.keys(this.$route.query).length);
    console.log(this.$route.query);

    if (Object.keys(this.$route.query).length == 0) {
      this.getDataList();
    } else {
      this.dataForm.projectId = this.$route.query.projectId;
      if (this.$route.query.statisticsTime) {
        this.dataForm.startSnapTime = this.$route.query.statisticsTime[0];
        this.dataForm.endSnapTime = this.$route.query.statisticsTime[1];
        this.dateRange1 = this.$route.query.statisticsTime;
      }
      this.dataForm.status = this.$route.query.status
        ? this.$route.query.status
        : this.$route.query.status === 0
        ? this.$route.query.status
        : null;
      this.$nextTick(() => {
        this.getDataList();
      });
    }
  },
  mounted() {
    this.getProject();
    this.getCompany();
  },
  methods: {
    timeChange(e, index) {
      console.log(e, index);
      if (index === 1) {
        if (e) {
          this.dataForm.startSnapTime = e[0];
          this.dataForm.endSnapTime = e[1];
        } else {
          this.dataForm.startSnapTime = null;
          this.dataForm.endSnapTime = null;
        }
      } else {
        if (e) {
          this.dataForm.startDate = e[0];
          this.dataForm.endDate = e[1];
        } else {
          this.dataForm.startDate = null;
          this.dataForm.endDate = null;
        }
      }
    },
    // 处理数组
    getArr(e) {
      return e.split(",");
    },

    // 查看异常
    infoHandle(id) {
      this.infoVisible = true;
      // 保存本次id
      this.tempid = id;
      console.log(this.tempid);
      this.pageParams.page = 1;
      this.$nextTick(() => {
        this.$refs.leaderInfo.init(id);
      });
    },
    // 导出
    handleExport() {
      this.$alert("导出任务已生成，请在“台账导出任务”中查看进度及结果", {
        confirmButtonText: "确定",
        callback: (action) => {
          console.log(action);
          // console.log(this.dataForm.startSnapTime,
          //           this.dataForm.endSnapTime,"---------"
          if (action === "confirm") {
            // this.$router.push({ name: 'Accountexport' })
            var ids = this.dataListSelections.map((item) => {
              return item.id;
            });
            var startSnapTime = this.dataForm.startSnapTime;
            var endSnapTime = this.dataForm.endSnapTime;
            var startDate = this.dataForm.startDate;
            var endDate = this.dataForm.endDate;
            var status = this.dataForm.status;
            var auditstatus = this.dataForm.auditstatus;
            var company = this.dataForm.company;
            var projectId = this.dataForm.projectId;
            var carCode = this.dataForm.carCode;
            var selectAll = this.dataForm.selectAll;

            this.$http({
              url: this.$http.adornUrl("/generator/bcarledger/handleExport"),
              method: "get",
              params: this.$http.adornParams({
                // ids: ids.join(","),
                startSnapTime,
                endSnapTime,
                startDate,
                endDate,
                status,
                auditstatus,
                company,
                projectId,
                carCode,
                selectAll,
              }),
            }).then(({ data }) => {
              console.log(data);
              if (data && data.code === 0) {
                this.dataList = data.page.list;
                this.totalPage = data.page.totalCount;
              } else {
                this.dataList = [];
                this.totalPage = 0;
              }
            });
            // this.$router.push({
            //   name: "management-Accountexport",
            // });
          }
        },
      });

      // let ids = this.dataListSelections.map(item => {
      //   return item.id;
      // });
      // if (ids.length > 0) {
      //   this.$http({
      //     url: this.$http.adornUrl(
      //       `/generator/bcarledger/handleExport?ids=${ids}`
      //     ),
      //     method: "get",
      //     responseType: "blob"
      //   }).then(({ data }) => {
      //     console.log(data, "data");
      //     const blob = new Blob([data], { type: "application/vnd.ms-excel" });
      //     let a = document.createElement("a");
      //     a.download = "台账管理.xlsx";
      //     a.href = URL.createObjectURL(blob);
      //     document.getElementsByTagName("body")[0].appendChild(a);
      //     a.click();
      //     a.parentNode.removeChild(a);
      //   });
      // } else {
      //   this.$http({
      //     url: this.$http.adornUrl(`/generator/bcarledger/handleExport`),
      //     method: "get",
      //     responseType: "blob"
      //   }).then(({ data }) => {
      //     console.log(data, "data");
      //     const blob = new Blob([data], { type: "application/vnd.ms-excel" });
      //     let a = document.createElement("a");
      //     a.download = "台账管理.xlsx";
      //     a.href = URL.createObjectURL(blob);
      //     document.getElementsByTagName("body")[0].appendChild(a);
      //     a.click();
      //     a.parentNode.removeChild(a);
      //   });
      // }
    },
    // 获取所属项目
    getProject() {
      this.$http({
        url: this.$http.adornUrl(`/sys/project/management/list`),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.projectList = data.list;
        }
      });
    },
    // 获取车辆所属公司
    getCompany() {
      this.$http({
        url: this.$http.adornUrl(`/sys/bcompany/data`),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.companyList = data.list;
        }
      });
    },
    // 获取数据列表
    getDataList(flag) {
      if (flag) {
        this.pageParams.page = 1;
      }
      if (
        JSON.parse(sessionStorage.getItem("permissions")).indexOf("selectAll") >
        -1
      ) {
        this.dataForm.selectAll = 1;
      } else if (
        JSON.parse(sessionStorage.getItem("permissions")).indexOf(
          "selectAll"
        ) === -1
      ) {
        this.dataForm.selectAll = 0;
      }
      this.dataListLoading = true;
      let params = { ...this.pageParams, ...this.dataForm };

      params.ledgerId = this.tempid;

      console.log(params);
      console.log(this.tempid + "---------------------");
      this.$http({
        url: this.$http.adornUrl("/generator/bcarledger/page"),
        method: "get",
        params: this.$http.adornParams(params),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageParams.limit = val;
      this.pageParams.page = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      console.log(val);
      this.pageParams.page = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.id;
          });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/generator/bcarledger/delete"),
          method: "post",
          data: this.$http.adornData(ids, false),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              },
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },

    //查看轨迹图
    checkHandle(id) {
      this.trackVisible = true;
      this.$nextTick(() => {
        this.$refs.leaderTrack.init(id);
      });
    },

    // 审核
    auditHandle(id, flag, row) {
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.id;
          });
      this.auditVisible = true;
      this.$nextTick(() => {
        this.$refs.ledgerAudit.init(ids, flag, row);
      });
    },

    // 批量审核
    batchAudit() {},
  },
};
</script>
